 #!/usr/bin/env python3
"""
调试气象和负荷数据
"""

import sys
import os
sys.path.append('.')

from backend.config.database import get_db_session
from backend.entities.weather_daily import WeatherDaily
from backend.entities.load_data_new import LoadData
from datetime import datetime, timedelta

def debug_weather_data():
    """调试气象和负荷数据"""
    print('开始调试气象和负荷数据...')
    
    # 获取数据库会话
    db = get_db_session()
    
    try:
        # 检查日期范围
        start_date = datetime(2025, 6, 20).date()
        end_date = datetime(2025, 7, 19).date()
        
        print(f'检查日期范围: {start_date} 到 {end_date}')
        
        # 检查气象数据
        weather_count = db.query(WeatherDaily).filter(
            WeatherDaily.dt >= start_date,
            WeatherDaily.dt <= end_date
        ).count()
        
        print(f'气象数据记录数: {weather_count}')
        
        # 检查负荷数据
        load_count = db.query(LoadData).filter(
            LoadData.dt >= start_date,
            LoadData.dt <= end_date
        ).count()
        
        print(f'负荷数据记录数: {load_count}')
        
        # 检查具体的数据
        print('\n检查具体数据:')
        current_date = start_date
        data_count = 0
        
        while current_date <= end_date:
            weather_data = db.query(WeatherDaily).filter(WeatherDaily.dt == current_date).first()
            load_data = db.query(LoadData).filter(LoadData.dt == current_date).first()
            
            if weather_data and load_data:
                print(f'✅ {current_date}: 气象和负荷数据都存在')
                data_count += 1
                
                # 检查负荷数据的有效性
                load_values = []
                for i in range(1, 97):
                    load_val = getattr(load_data, f't{i}', None)
                    if load_val is not None and str(load_val).strip() != '':
                        try:
                            load_values.append(float(str(load_val)))
                        except (ValueError, TypeError):
                            continue
                
                if load_values:
                    avg_load = sum(load_values) / len(load_values)
                    print(f'   平均负荷: {avg_load:.2f} MW')
                else:
                    print(f'   ❌ 负荷数据无效')
            else:
                print(f'❌ {current_date}: 数据不完整')
                if weather_data:
                    print(f'   气象数据: 最高温度={weather_data.t_max}, 最低温度={weather_data.t_min}, 降水量={weather_data.precip}, 湿度={weather_data.humidity}')
                if load_data:
                    print(f'   负荷数据: 存在但需要检查有效性')
            
            current_date += timedelta(days=1)
        
        print(f'\n总结: 在30天中有 {data_count} 天有完整的气象和负荷数据')
        
        if data_count == 0:
            print('❌ 没有找到有效的数据，将使用模拟数据')
        else:
            print('✅ 找到有效数据，可以生成真实的时间序列图表')
            
    except Exception as e:
        print(f'调试失败: {e}')
    finally:
        db.close()

if __name__ == '__main__':
    debug_weather_data()